<?php

/**
 * @package    Europa
 * @subpackage Session
 */

/**
 * Allows manipulation sessions in an object-orented fashion. Sessions are created as a sub-session of the global
 * $_SESSION array. This means you can organize these "sub-sessions" as namespaces rather than working directly with
 * the global scope.
 */
class Europa_Session
{
	private
		/**
		 * Contains the custom session id used to construct this session.
		 * 
		 * @var mixed
		 */
		$_id = null;
	
	
	
	/**
	 * Constructs a new/existing session. If the session key/id already exists, then the session is resumed, otherwise
	 * a new session is created.
	 * 
	 * @param string $id The session id.
	 */
	public function __construct($id = 'default')
	{
		// start the session if not started yet
		if (!session_id())
			session_start();
		
		$this->_id = $id;
		
		// preset this namespace if not set yet
		if (!isset($_SESSION[$this->_id]))
			$_SESSION[$this->_id] = array();
	}
	
	/**
	 * Sets a session variable.
	 * 
	 * @param string $name  The session varible to set.
	 * @param mixed  $value The value of the session variable to set.
	 * 
	 * @return void
	 */
	public function __set($name, $value)
	{
		$_SESSION[$this->_id][$name] = $value;
	}
	
	/**
	 * Returns a session variable or null if not found.
	 * 
	 * @param string $name The session variable to retrieve.
	 * 
	 * @return mixed
	 */
	public function __get($name)
	{
		return isset($_SESSION[$this->_id][$name])
			? $_SESSION[$this->_id][$name]
			: null;
	}
	
	/**
	 * Unsets the current session from the $_SESSION global.
	 * 
	 * @return void
	 */
	public function __destroy()
	{
		unset($_SESSION[$this->_id]);
	}
}